package com.iu.service.impl.author;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iu.bean.author.Permission;
import com.iu.bean.author.Role;
import com.iu.bean.author.User;
import com.iu.bean.author.UserRole;
import com.iu.dao.author.UserDao;
import com.iu.service.author.UserService;
import com.iu.util.PasswordHelper;

/**
 * <p>User: Zhang Kaitao
 * <p>Date: 14-1-28
 * <p>Version: 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    
    private PasswordHelper passwordHelper = new PasswordHelper();

    /**
     * 创建用户
     * @param user
     */
    public User createUser(User user) {
        //加密密码
        passwordHelper.encryptPassword(user);
        userDao.createUser(user);
        return user;
    }

    /**
     * 修改密码
     * @param userId
     * @param newPassword
     */
    public void changePassword(Long userId, String newPassword) {
        User user =userDao.findOne(userId);
        user.setPassword(newPassword);
        passwordHelper.encryptPassword(user);
        userDao.updateUser(user);
    }

    /**
     * 添加用户-角色关系
     * @param userId
     * @param roleIds
     */
    public int correlationRoles(Long userId, Long... roleIds) {
        List<UserRole> userRoles = new ArrayList<UserRole>();
        
        for( Long roleId : roleIds ){
            UserRole userRole = new UserRole();
            userRole.setRoleId( roleId );
            userRole.setUserId( userId );
            userRoles.add( userRole );
        }
        
        return userDao.correlationRoles( userRoles );
    }


    /**
     * 移除用户-角色关系
     * @param userId
     * @param roleIds
     */
    public void uncorrelationRoles(Long userId, Long... roleIds) {
        List<UserRole> userRoles = new ArrayList<UserRole>();
        
        for( Long roleId : roleIds ){
            UserRole userRole = new UserRole();
            userRole.setRoleId( roleId );
            userRole.setUserId( userId );
            userRoles.add( userRole );
        }
        userDao.uncorrelationRoles(userRoles);
    }

    /**
     * 根据用户名查找用户
     * @param username
     * @return
     */
    public User findByUsername(String username) {
        return userDao.findByUsername(username);
    }

    /**
     * 根据用户名查找其角色
     * @param username
     * @return
     */
    public List<Role> findRoles(String username) {
        return userDao.findRoles(username);
    }

    /**
     * 根据用户名查找其权限
     * @param username
     * @return
     */
    public List<Permission> findPermissions(String username) {
        return userDao.findPermissions(username);
    }

}
